<template>
  <el-select ref="selectTree" v-model="form.Id" filterable placeholder="请选择" style="width:100%">
    <el-option :key="form.Id" :value="form.Id" :label="form.label" style="height: auto" hidden />
    <el-tree ref="tree" :data="data" :props="defaultProps" :node-key="defaultProps.value" @node-click="handleClickNode" />
  </el-select>
</template>

<script>
export default {
  data() {
    return {
      data: [{
        Id: 1,
        label: '一级 1',
        children: [
          {
            Id: 11,
            label: '二级 1-1',
            children: [{
              Id: 111,
              label: '三级 1-1-1'
            }]
          }]
      },
      ],
      defaultProps: {
        /** 唯一标识 **/
        value: 'Id',
        /** 标签显示 **/
        label: 'name',
        /** 子级 **/
        children: 'children'
      },
      form: {
        id: "",
        label: ""
      }
    }
  },
  mounted() {
    this.getRegion();//籍贯
  },
  methods: {
    // 行政区域接口-----------------
    getRegion() {
      this.$http.get(`/sys/region/tree`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        // 获取一级目录
        let oneArr = [], twoArr = []
        res.data.forEach(ele => {
          if (ele.pid == 0) {
            ele.children = [];
            oneArr.push(ele)
          } else {
            twoArr.push(ele)
          }
        });
        // 获取二级目录
        oneArr.forEach(it => {
          twoArr.forEach(item => {
            if (it.id == item.pid) {
              item.children = [];
              it.children.push(item);
            }
          })
        });
        // 获取三级目录
        oneArr.forEach(it => {
          it.children.forEach(its => {
            twoArr.forEach(item => {
              if (its.id == item.pid) {
                its.children.push(item)
              }
            })
          })
        });
        this.data = oneArr
      })
    },
    //节点点击事件
    handleClickNode(data) {
      this.form.id = data.id
      this.form.label = data.name
      this.$emit('child', this.form.label)
      // 选择器执行完成后，使其失去焦点隐藏下拉框的效果
      this.$refs.selectTree.blur()
    },
  }
}
</script>
